package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	//insert()
	query()
}

func query() {
	db, err := sql.Open("mysql", "root:asdf1234@tcp(192.168.84.128:3306)/test?charset=utf8")
	if err != nil {
		fmt.Println("link db error")
		return
	}
	rows, err := db.Query("select * from push_content;")
	if err != nil {
		fmt.Println("query db error")
		return
	}
	columns, _ := rows.Columns()
	fmt.Println(len(columns))
	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for i := range values {
		scanArgs[i] = &values[i]
	}

	for rows.Next() {
		//将行数据保存到record字典
		err = rows.Scan(scanArgs...)
		record := make(map[string]string)
		for i, col := range values {
			if col != nil {
				record[columns[i]] = string(col.([]byte))
			}
		}
		fmt.Println(record)
	}
}
func insert() {
	db, err := sql.Open("mysql", "root:asdf1234@tcp(192.168.84.128:3306)/test?charset=utf8")
	if err != nil {
		fmt.Println("open db error")
		return
	}

	stmt, err := db.Prepare("insert into push_content(name, creater, company, type, cpath, ctime, ttime, ptime, money) values(?, ?, ?, ?, ?, ?, ?, ?, ?);")
	if err != nil {
		fmt.Println("prepare db error")
		return
	}

	res, err := stmt.Exec("name2", "creater2", "company2", "typ2", "path2", "20170504110911", "20170504110911", "20170504110912", "1000")
	if err != nil {
		fmt.Println("exec db error")
		return
	}

	id, err := res.LastInsertId()
	checkErr(err)

	fmt.Println(id)
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
